package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询店铺类型列表
     * @return
     */
    @Override
    public Result queryList() {
        //优先查缓存
        String shopTypeListJsonStr = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE_KEY);
        //缓存里有数据，直接返回
        if (!StrUtil.isBlank(shopTypeListJsonStr)) {
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypeListJsonStr, ShopType.class);
            return Result.ok(shopTypeList);
        }
        //若不存在则查数据库
        List<ShopType> dbShopTypeList = query().orderByAsc("sort").list();
        //数据库中不存在，返回错误信息
        if (dbShopTypeList == null || dbShopTypeList.isEmpty()) {
            return Result.fail("店铺列表不存在！");
        }
        //数据库中存在，写入redis
        String dbShopTypeListJsonStr = JSONUtil.toJsonStr(dbShopTypeList);
        redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE_KEY, dbShopTypeListJsonStr);
        //返回
        return Result.ok(dbShopTypeList);
    }
}
